package org.example.Util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

public class JsonUtil {
    private static final ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 将对象写入HTTP响应为JSON格式
     * @param response HTTP响应对象
     * @param obj 要序列化的对象
     * @throws IOException 如果发生I/O错误
     */
    public static void writeJsonResponse(HttpServletResponse response, Object obj) throws IOException {
        response.setContentType("application/json");
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());
        try {
            objectMapper.writeValue(response.getWriter(), obj);
        } catch (JsonProcessingException e) {
            throw new IOException("Failed to serialize object to JSON", e);
        }
    }

    /**
     * 从HTTP请求中解析JSON数据
     * @param request HTTP请求对象
     * @param clazz 目标Java类型
     * @param <T> 泛型类型
     * @return 解析后的Java对象
     * @throws IOException 如果发生I/O错误或JSON解析失败
     */
    public static <T> T parseJsonRequest(HttpServletRequest request, Class<T> clazz) throws IOException {
        try (InputStream inputStream = request.getInputStream()) {
            return objectMapper.readValue(inputStream, clazz);
        } catch (JsonMappingException e) {
            throw new IOException("Invalid JSON format", e);
        } catch (JsonProcessingException e) {
            throw new IOException("Failed to parse JSON", e);
        }
    }

    /**
     * 从字符串解析JSON数据
     * @param json JSON字符串
     * @param clazz 目标Java类型
     * @param <T> 泛型类型
     * @return 解析后的Java对象
     * @throws IOException 如果JSON解析失败
     */
    public static <T> T parseJsonString(String json, Class<T> clazz) throws IOException {
        try {
            return objectMapper.readValue(json, clazz);
        } catch (JsonProcessingException e) {
            throw new IOException("Failed to parse JSON string", e);
        }
    }
}